package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.CoContract;
import com.ruoyi.system.service.ICoContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 合同信息
 */
@RestController
@RequestMapping("/system/contract")
public class CoContractController extends BaseController {
    @Autowired
    private ICoContractService contractService;

    /**
     * 获取合同列表
     */
    @PreAuthorize("@ss.hasPermi('system:contract:list')")
    @GetMapping("/list")
    public TableDataInfo list(CoContract contract) {
        startPage();
        List<CoContract> list = contractService.selectContractList(contract);
        return getDataTable(list);
    }

    /**
     * 获取用户的合同列表
     */
    @PreAuthorize("@ss.hasPermi('system:contract:list')")
    @GetMapping("/user/{userId}")
    public TableDataInfo listByUser(@PathVariable("userId") Long userId) {
        startPage();
        List<CoContract> list = contractService.selectContractsByUserId(userId);
        return getDataTable(list);
    }

    /**
     * 获取合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:contract:query')")
    @GetMapping(value = "/{contractId}")
    public AjaxResult getInfo(@PathVariable("contractId") Long contractId) {
        return success(contractService.selectContractById(contractId));
    }

    /**
     * 新增合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:add')")
    @Log(title = "合同管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CoContract contract) {
        // 设置当前用户ID
        contract.setUserId(SecurityUtils.getLoginUser().getUserId());
        return toAjax(contractService.insertContract(contract));
    }

    /**
     * 修改合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:edit')")
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CoContract contract) {
        return toAjax(contractService.updateContract(contract));
    }

    /**
     * 删除合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:remove')")
    @Log(title = "合同管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{contractIds}")
    public AjaxResult remove(@PathVariable Long[] contractIds) {
        return toAjax(contractService.deleteContractByIds(contractIds));
    }

    /**
     * 更新合同状态
     */
    @PreAuthorize("@ss.hasPermi('system:contract:edit')")
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{contractId}/{status}")
    public AjaxResult updateStatus(@PathVariable("contractId") Long contractId, @PathVariable("status") Integer status) {
        return toAjax(contractService.updateContractStatus(contractId, status));
    }

    /**
     * 上传合同文件
     */
    @PreAuthorize("@ss.hasPermi('system:contract:upload')")
    @Log(title = "合同管理", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // TODO: 实现文件上传逻辑
            // 1. 检查文件类型和大小
            // 2. 生成文件存储路径
            // 3. 保存文件
            // 4. 返回文件路径
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载合同文件
     */
    @PreAuthorize("@ss.hasPermi('system:contract:download')")
    @GetMapping("/download/{contractId}")
    public AjaxResult downloadFile(@PathVariable("contractId") Long contractId) {
        try {
            CoContract contract = contractService.selectContractById(contractId);
            if (contract == null || contract.getFilePath() == null) {
                return AjaxResult.error("文件不存在");
            }
            // TODO: 实现文件下载逻辑
            // 1. 检查文件是否存在
            // 2. 读取文件
            // 3. 返回文件流
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取合同统计信息
     */
    @GetMapping("/stats")
    public AjaxResult getContractStats(@RequestParam(required = false) Long userId) {
        Map<String, Object> stats = contractService.selectContractStatsByUserId(userId);
        return success(stats);
    }

    /**
     * 获取合同类型统计信息
     */
    @GetMapping("/typeStats")
    @PreAuthorize("@ss.hasPermi('system:contract:query')")
    public AjaxResult getContractTypeStats(@RequestParam(required = false) Long userId) {
        List<Map<String, Object>> stats = contractService.selectContractTypeStats(userId);
        return success(stats);
    }
}
